package com.jiangnan.utils;

import jpcap.packet.Packet;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.util.LinkedList;
import java.util.Random;

/**
 *
 * 对于jtable得一些操作
 * @author chenliang
 * @email wschenliang@aliyun.com
 */
public class JTableUtil {

    private static JTable jTable;

    public static void setJTableComponent(JTable table) {
        jTable = table;
    }

    public static DefaultTableModel getTableModel() {
        return (DefaultTableModel) jTable.getModel();
    }

    /**
     * 从表格中获取数据
     *
     * @return 所有的packet
     */
    public static LinkedList<Packet> getPacketsFromJTable() {
        DefaultTableModel model = (DefaultTableModel) jTable.getModel();
        int rowCount = model.getRowCount();
        LinkedList<Packet> packets = new LinkedList<>();
        for (int i = 0; i < rowCount; i++) {
            String info = (String) model.getValueAt(i, 6);
            if (StringUtils.isNotBlank(info)) {
                Packet p = FastjsonUtils.json2Object(info, Packet.class);
                packets.add(p);
            }
        }
        return packets;
    }

    private static final Random rand = new Random();

    public static void resortTable() {
        DefaultTableModel model = (DefaultTableModel) jTable.getModel();
        int rowCount = model.getRowCount();
        if (rowCount < 2) {
            return;
        }
        int columnCount = model.getColumnCount();
        Object[][] s = new Object[rowCount][columnCount];
        for (int i = 0; i < rowCount; i++) {
            for (int j = 0; j < columnCount; j++) {
                s[i][j] = model.getValueAt(i,j);
            }
        }
        //对s的行进行洗牌算法
        for (int i = rowCount; i > 0; i--) {
            int randInd = rand.nextInt(i);
            Object[] temp = s[randInd];
            temp[0] = i;

            s[randInd] = s[i - 1];
            s[i - 1] = temp;
        }
        model.setRowCount(0);
        for (Object[] objects : s) {
            model.addRow(objects);
        }
    }


    /**
     * 清空表格
     */
    public static void clearJTable() {
        DefaultTableModel model = (DefaultTableModel) jTable.getModel();
        model.setRowCount(0);
        PacketUtil.init();
    }


    public static LinkedList<String> getModelsFromJTable() {
        DefaultTableModel model = (DefaultTableModel) jTable.getModel();
        int rowCount = model.getRowCount();
        LinkedList<String> list = new LinkedList<>();
        for (int i = 0; i < rowCount; i++) {
            String s = (String) model.getValueAt(i, 7);
            if (StringUtils.isNotBlank(s)) {
                list.add(s.trim());
            }
        }
        return list;
    }
}
